<script setup lang="ts">
import type {
  FormInstance,
  FormItemInstance,
} from 'element-plus'
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'

import {
  RenderWarningTag,
  renderState,
  renderType,
} from '@/mixins/Warning'

import { alarmApi } from '@/api'
import { WARNING_WORK_ORDER_STATES } from '@/enum'

import type {
  WarningInfo,
  WorkOrderInfo,
  WorkOrderUser,
} from '@/types'

const props = defineProps<{
  warningInfo?: WarningInfo
  workOrderInfo?: WorkOrderInfo
  workOrderUsers?: WorkOrderUser[]
}>()
const emits = defineEmits<{
  (e: 'save-success'): void
}>()
const dialogRef = ref<InstanceType<typeof CustomDialog>>()
const formRef = ref<FormInstance>()

const info: {
  auditContent: string
  state: WARNING_WORK_ORDER_STATES
} = reactive({
  auditContent: '',
  state: WARNING_WORK_ORDER_STATES.SOLVED,
})
const auditContentLabel = computed(() => {
  return info.state === WARNING_WORK_ORDER_STATES.SOLVED
    ? '审核内容描述'
    : '驳回原因描述'
})
const rules = computed(() => {
  return {
    // state: [
    //   {
    //     required: true,
    //     message: '请选择审核状态'
    //   }
    // ],
    auditContent: [
      {
        // 驳回时 驳回原因必填
        required:
          info.state === WARNING_WORK_ORDER_STATES.REJECTED,
        message:
          `请输入${
          auditContentLabel.value
          }，字数在200个以内`,
      },
    ],
  }
})
const auditContentFormItemRef = ref<FormItemInstance>()
function whenStateChange() {
  setTimeout(() => {
    auditContentFormItemRef.value?.clearValidate()
  }, 20)
}

function open() {
  info.auditContent = ''
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

async function clickSave(done: any) {
  const isValid = await formRef.value
    ?.validate()
    .catch(() => {
      done()
    })
  if (isValid) {
    try {
      await alarmApi.updateWorkOrder({
        id: props.workOrderInfo?.id!,
        workOrderNum: props.warningInfo?.workOrderNum!,
        state: info.state,
        auditContent: info.auditContent,
      })
      done()
      close()
      ElMessage.success('保存成功')
      emits('save-success')
    }
    catch (e) {
      done()
      console.log(e)
    }
  }
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="告警审核"
    need-saving
    class="custom-dialog"
    @confirm="clickSave"
  >
    <ElDescriptions
      v-if="warningInfo"
      title="告警信息"
      border
      :column="2"
    >
      <ElDescriptionsItem label="告警类型">
        <RenderWarningTag
          :warning-info="warningInfo"
          :render="renderType"
        />
      </ElDescriptionsItem>
      <ElDescriptionsItem label="告警持续时间">
        {{ warningInfo.warningLastTime }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="指标名称">
        {{ warningInfo.indicatorName }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="测点点位号">
        {{ warningInfo.indicatorCode }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="设备名称/点位" :span="2">
        {{ warningInfo.pointNameFull }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="告警开始时间" :span="2">
        {{ warningInfo.warningStartTime }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="告警内容" :span="2">
        {{ warningInfo.warningContent }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="告警状态">
        <RenderWarningTag
          :warning-info="warningInfo"
          :render="renderState"
        />
      </ElDescriptionsItem>
    </ElDescriptions>
    <ElDescriptions
      v-if="workOrderInfo"
      title="处理信息"
      border
      :column="2"
      class="margin-top-sm"
    >
      <ElDescriptionsItem label="工单号" :span="2">
        {{ workOrderInfo.workOrderNum }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="处理人" :span="2">
        <div class="overflow-hidden">
          <ElTooltip
            v-for="item in workOrderUsers"
            :key="item.userId"
            :content="`账号：${item.loginName}`"
            placement="top"
          >
            <ElTag style="float: left; margin-right: 10px">
              {{ item.userName }}
            </ElTag>
          </ElTooltip>
        </div>
      </ElDescriptionsItem>
      <ElDescriptionsItem label="工单创建时间">
        {{ workOrderInfo.creationTime }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="期望处理结束时间">
        {{ workOrderInfo.processingEndTime }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="审核提交人" :span="2">
        {{ workOrderInfo.userName }}
        {{
          workOrderInfo.loginName
            ? `（${workOrderInfo.loginName}）`
            : ''
        }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="审核提交时间">
        {{ workOrderInfo.submitTime }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="处理时间">
        {{ workOrderInfo.processingTime }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="处理内容描述" :span="2">
        {{ workOrderInfo.processingContent }}
      </ElDescriptionsItem>
    </ElDescriptions>
    <div
      class="el-descriptions__header"
      style="margin-bottom: 16px; margin-top: 16px"
    >
      <div class="el-descriptions__title">
        审核信息
      </div>
    </div>
    <ElForm
      ref="formRef"
      :model="info"
      :rules="rules"
      label-position="top"
      style="margin-top: 12px"
    >
      <ElFormItem label="审核状态" prop="state">
        <ElRadioGroup
          v-model="info.state"
          @change="whenStateChange"
        >
          <ElRadio
            :label="WARNING_WORK_ORDER_STATES.SOLVED"
          >
            通过
          </ElRadio>
          <ElRadio
            :label="WARNING_WORK_ORDER_STATES.REJECTED"
          >
            驳回
          </ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem
        ref="auditContentFormItemRef"
        :label="auditContentLabel"
        prop="auditContent"
      >
        <ElInput
          v-model.trim="info.auditContent"
          type="textarea"
          :maxlength="200"
          :minlength="1"
          :autosize="{
            minRows: 4,
            maxRows: 8,
          }"
          :placeholder="`请输入${auditContentLabel}，字数在200个以内`"
        />
      </ElFormItem>
    </ElForm>
  </CustomDialog>
</template>
